package com.ytjj.quartz.task;

import com.ytjj.qmyx.mall.mapper.FrontCategoryMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.quartz.dao.ProductDao;
import com.ytjj.quartz.model.ProductCategoryResp;
import com.ytjj.quartz.service.ProductInfoService;
import com.ytjj.quartz.service.SpecialRankService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SpecialRankTask {
    @Autowired
    private SpecialRankService specialRankService;
    @Autowired
    private ProductInfoService productInfoService;
    @Resource
    private FrontCategoryMapper frontCategoryMapper;
    @Resource
    private ProductDao productDao;

    /**
     * 定时生成分类排行榜
     */
    @Scheduled(cron = "0 7/30 * * * ?")
    public void updateProductStock() {
        FrontCategoryExample example = new FrontCategoryExample();
        example.createCriteria().andPidEqualTo(0).andIsDeleteEqualTo(new Byte("0")).andStatusEqualTo(new Byte("1"));
        List<FrontCategory> frontCategorys = frontCategoryMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(frontCategorys)) {
            return;
        }
        frontCategorys.stream().forEach(item -> {
            specialRankService.deleteBySpecialId(item.getId());
            //获取分类id
            String categoryListStr = item.getCategoryList();
            if (StringUtils.isEmpty(categoryListStr)) {
                return;
            }
            List<String> categoryIdStrs = Arrays.asList(categoryListStr.split(","));
            List<Integer> ids = categoryIdStrs.stream().map(id -> Integer.parseInt(id)).collect(Collectors.toList());

            //通过专区里的分类id获取到分类对象集合
            List<ProductCategoryResp> list = productDao.selectCategoryByIds(ids);
            //分类集合进行排序(三级放二级,二级放一级里)
            List<ProductCategoryResp> productCategoryResp = productInfoService.getProductCategoryResps(list);
            //获得层级关系的最后一级id
            List<Integer> categoryIds = productInfoService.getCategoryIds(productCategoryResp);
            if(categoryIds.size() == 0){
                return;
            }

            specialRankService.generateDataByTask(categoryIds, item.getId(), item.getTitle());
        });
    }
}
